import React, { useState, forwardRef, useImperativeHandle, useEffect, useRef } from 'react';
import ReactDOM from 'react-dom';
import { Button, Select, Space, message, Spin, Drawer, Switch, InputNumber, Divider } from 'antd';
import { LoadingOutlined, SettingOutlined, CommentOutlined } from '@ant-design/icons';
import MonacoEditor from 'react-monaco-editor';
import * as monaco from 'monaco-editor';
import 'monaco-editor/esm/vs/language/typescript/monaco.contribution';
import 'monaco-editor/esm/vs/basic-languages/javascript/javascript.contribution';
import { initializeTypeScriptDefaults } from '../../utils/monaco-init';
import { aiApi } from '../../api/services/AI/aiApi';

const { Option } = Select;

const defaultCode = {
  cpp: '#include <iostream>\nusing namespace std;\n\nint main() {\n    string s;\n    cin >> s;\n    cout << "Hello, " << s << "!\\n";\n    return 0;\n}',
  python: 'name = input()\nprint(f"Hello, {name}!")',
  java: 'import java.util.Scanner;\n\npublic class Main {\n    public static void main(String[] args) {\n        Scanner scanner = new Scanner(System.in);\n        String name = scanner.nextLine();\n        System.out.println("Hello, " + name + "!");\n    }\n}',
  javascript: 'const name = prompt("Enter your name:");\nconsole.log(`Hello, ${name}!`);'
};

const runCode = async (code: string, language: string, input: string): Promise<{ output: string; error: string }> => {
  try {
    const response = await fetch(`${import.meta.env.VITE_API_BASE_URL}/api/run`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ code, language, input }),
    });

    if (!response.ok) {
      throw new Error('服务器响应错误');
    }

    return await response.json();
  } catch (error) {
    return {
      output: '',
      error: error instanceof Error ? error.message : '请求失败'
    };
  }
};

interface CodeEditorProps {
  onCodeChange?: (code: string) => void;
  onLanguageChange?: (language: string) => void;
  onRunStart?: () => void; // New prop to signal run start
  onRunComplete?: (result: { output: string; error: string; loading: boolean }) => void; // New prop to pass run result
  testCaseInput?: string; // Receive testCaseInput from parent
  initialCode?: string; // Optional initial code
  initialLanguage?: string; // Optional initial language
}

// 定义CodeEditor引用暴露的方法
export interface CodeEditorRef {
  handleRunCode: () => Promise<void>;
  handleSubmitCode: () => void;
}

const CodeEditor = forwardRef<CodeEditorRef, CodeEditorProps>(({
  onCodeChange,
  onLanguageChange,
  onRunStart,
  onRunComplete,
  testCaseInput,
  initialCode,
  initialLanguage
}, ref) => {
  const [code, setCode] = useState(initialCode || defaultCode.cpp);
  const [language, setLanguage] = useState(initialLanguage || 'cpp');
  const [theme, setTheme] = useState('vs');
  const [loading, setLoading] = useState(false);
  const [editorLoading, setEditorLoading] = useState(true);
  const [editorMounted, setEditorMounted] = useState(false);
  const [editorError, setEditorError] = useState<string | null>(null);
  const editorRef = useRef<any>(null);
  const monacoRef = useRef<typeof monaco | null>(null);

  // 设置面板状态
  const [settingsVisible, setSettingsVisible] = useState(false);

  // 编辑器设置状态
  const [settings, setSettings] = useState({
    enableAICompletion: true, // 是否启用AI代码补全
    enableCodeSuggestions: true, // 是否启用内置代码提示
    completionDelay: 1500, // 代码补全间隔时间（毫秒）
    enableMinimap: true, // 是否启用迷你地图
    fontSize: 14, // 字体大小
    showLineNumbers: true, // 是否显示行号
    wordWrap: true, // 是否自动换行
    autoIndent: true, // 是否自动缩进
    formatOnPaste: true, // 粘贴时是否格式化
    mouseWheelZoom: true // 是否启用鼠标滚轮缩放
  });

  // AI补全相关状态
  const copilotTimerRef = useRef<number | null>(null);
  const abortControllerRef = useRef<AbortController | null>(null);
  const keyDownDisposableRef = useRef<monaco.IDisposable | null>(null);
  const mouseDownDisposableRef = useRef<monaco.IDisposable | null>(null);
  const inlineCompletionDisposeRef = useRef<monaco.IDisposable | null>(null);

  // AI注释相关状态
  const [commentLoading, setCommentLoading] = useState(false);

  // 光标loading状态
  const [cursorLoading, setCursorLoading] = useState({
    left: 0,
    top: 0,
    visible: 'hidden' as React.CSSProperties['visibility']
  });

  // 预加载编辑器资源
  useEffect(() => {
    const preloadMonaco = async () => {
      try {
        // 预加载Monaco资源
        await import('../../utils/monaco-init');
      } catch (error) {
        console.error('Monaco初始化失败:', error);
      }
    };
    preloadMonaco();
  }, []);

  // 加载超时处理
  useEffect(() => {
    let timeoutId: number;

    if (editorLoading && !editorMounted) {
      timeoutId = window.setTimeout(() => {
        if (!editorMounted) {
          setEditorError('编辑器加载超时，请刷新页面重试');
          setEditorLoading(false);
        }
      }, 10000);
    }

    return () => {
      if (timeoutId) {
        clearTimeout(timeoutId);
      }
    };
  }, [editorLoading, editorMounted]);

  // 清理资源
  useEffect(() => {
    return () => {
      if (copilotTimerRef.current) {
        clearTimeout(copilotTimerRef.current);
      }
      if (abortControllerRef.current && !abortControllerRef.current.signal.aborted) {
        abortControllerRef.current.abort();
      }
      if (keyDownDisposableRef.current) {
        keyDownDisposableRef.current.dispose();
      }
      if (mouseDownDisposableRef.current) {
        mouseDownDisposableRef.current.dispose();
      }
      if (inlineCompletionDisposeRef.current) {
        inlineCompletionDisposeRef.current.dispose();
      }
    };
  }, []);

  const handleEditorChange = (value: string) => {
    setCode(value);
    onCodeChange?.(value);
  };

  const handleLanguageChange = (value: string) => {
    setLanguage(value);
    const newDefaultCode = defaultCode[value as keyof typeof defaultCode] || '';
    setCode(newDefaultCode);
    onCodeChange?.(newDefaultCode);
    onLanguageChange?.(value);
  };

  const handleThemeChange = (value: string) => {
    setTheme(value);
  };

  const handleRunCode = async () => {
    onRunStart?.();
    setLoading(true);
    const result = await runCode(code, language, testCaseInput || '');
    setLoading(false);
    onRunComplete?.({ ...result, loading: false });
  };

  const handleSubmitCode = () => {
    message.info('提交代码功能待实现');
  };

  // 处理AI代码注释
  const handleAIComment = async () => {
    if (!code.trim()) {
      message.warning('请先输入代码');
      return;
    }

    setCommentLoading(true);
    let commentCount = 0;

    try {
      console.log('开始AI流式代码注释请求...');

      // 流式注释回调函数
      const onStreamComment = async (comment: { lineNumber: number; comment: string }) => {
        console.log('收到流式注释:', comment);
        await applyCommentsToEditor([comment]);
        commentCount++;
      };

      const result = await aiApi.getCodeComments({
        code: code,
        language: language
      }, onStreamComment);

      console.log('AI代码注释完成，结果:', result);

      if (result.code === 1) {
        if (commentCount > 0) {
          message.success(`流式添加了 ${commentCount} 条注释`);
        } else {
          message.warning('AI未生成任何注释');
        }
      } else {
        message.warning(result.message || 'AI注释生成失败');
      }
    } catch (error) {
      console.error('AI代码注释失败:', error);
      message.error('AI代码注释失败，请重试');
    } finally {
      setCommentLoading(false);
    }
  };

  // 将注释应用到编辑器（支持流式添加）
  const applyCommentsToEditor = async (comments: { lineNumber: number; comment: string }[]) => {
    if (!editorRef.current || !monacoRef.current) {
      console.error('编辑器未初始化');
      return;
    }

    const editor = editorRef.current;
    const model = editor.getModel();

    if (!model) {
      console.error('编辑器模型未找到');
      return;
    }

    // 获取当前语言的注释语法
    const getCommentSyntax = (lang: string): string => {
      switch (lang) {
        case 'cpp':
        case 'java':
        case 'javascript':
        case 'typescript':
          return '//';
        case 'python':
          return '#';
        default:
          return '//';
      }
    };

    const commentPrefix = getCommentSyntax(language);

    // 获取当前代码的总行数
    const totalLines = model.getLineCount();

    // 批量编辑操作
    const edits: monaco.editor.IIdentifiedSingleEditOperation[] = [];

    for (const { lineNumber, comment } of comments) {
      // 验证行号有效性
      if (lineNumber < 1 || lineNumber > totalLines) {
        console.warn(`行号 ${lineNumber} 超出范围 (1-${totalLines})，跳过`);
        continue;
      }

      // 获取该行的内容
      const lineContent = model.getLineContent(lineNumber);

      // 检查该行是否已经有相同的注释内容
      if (lineContent.includes(comment)) {
        console.log(`第 ${lineNumber} 行已有相同注释，跳过`);
        continue;
      }

      // 在行末添加注释
      const lineEndColumn = model.getLineMaxColumn(lineNumber);
      const commentText = ` ${commentPrefix} ${comment}`;

      edits.push({
        range: {
          startLineNumber: lineNumber,
          startColumn: lineEndColumn,
          endLineNumber: lineNumber,
          endColumn: lineEndColumn
        },
        text: commentText,
        forceMoveMarkers: true
      });
    }

    if (edits.length > 0) {
      // 执行批量编辑
      editor.executeEdits('ai-comment', edits);

      // 更新代码状态
      const newCode = model.getValue();
      setCode(newCode);
      onCodeChange?.(newCode);

      console.log(`成功应用 ${edits.length} 条注释`);
    } else {
      console.log('没有需要添加的注释');
    }
  };

  // 处理设置变更
  const handleSettingChange = (key: string, value: any) => {
    setSettings(prev => ({
      ...prev,
      [key]: value
    }));
  };

  // 当设置变化时更新编辑器选项
  useEffect(() => {
    if (editorRef.current) {
      editorRef.current.updateOptions({
        minimap: { enabled: settings.enableMinimap },
        fontSize: settings.fontSize,
        lineNumbers: settings.showLineNumbers ? 'on' : 'off',
        wordWrap: settings.wordWrap ? 'on' : 'off',
        formatOnPaste: settings.formatOnPaste,
        autoIndent: settings.autoIndent ? 'full' : 'none',
        mouseWheelZoom: settings.mouseWheelZoom,
        // 内置代码提示设置（独立于AI补全）
        suggestOnTriggerCharacters: settings.enableCodeSuggestions,
        quickSuggestions: settings.enableCodeSuggestions ? {
          other: true,
          comments: true,
          strings: true
        } : false,
        parameterHints: { enabled: settings.enableCodeSuggestions },
        acceptSuggestionOnCommitCharacter: settings.enableCodeSuggestions,
        acceptSuggestionOnEnter: settings.enableCodeSuggestions ? 'on' : 'off',
        // AI内联补全设置（独立于内置代码提示）
        inlineSuggest: {
          enabled: settings.enableAICompletion,
          mode: 'prefix',
          suppressSuggestions: false
        }
      });
    }
  }, [settings]);

  // 检查是否应该触发AI补全（考虑设置）
  const shouldTriggerCompletionWithSettings = (prefixContent: string, suffixContent: string, context: any): boolean => {
    // 如果AI代码补全被禁用，不触发
    if (!settings.enableAICompletion) {
      return false;
    }
    return shouldTriggerCompletion(prefixContent, suffixContent, context);
  };

  // 切换到加载光标
  const switchToLoadingCursor = () => {
    try {
      const defaultCursor = document.querySelector('.cursors-layer .cursor') as HTMLDivElement;
      if (defaultCursor) {
        const defaultCursorRect = defaultCursor.getBoundingClientRect();
        const cursorLayer = document.querySelector('.monaco-editor .cursors-layer');

        if (cursorLayer) {
          const cursorLayerRect = cursorLayer.getBoundingClientRect();

          defaultCursor.style.display = 'none';
          setCursorLoading({
            left: defaultCursorRect.left - cursorLayerRect.left + 2,
            top: defaultCursorRect.top - cursorLayerRect.top + 2,
            visible: 'visible'
          });
        }
      }
    } catch (error) {
      console.warn('切换到loading光标失败:', error);
      // 降级到原有方案
      if (editorRef.current) {
        editorRef.current.updateOptions({ readOnly: true });
        document.body.style.cursor = 'wait';
      }
    }
  };

  // 切换到默认光标
  const switchToDefaultCursor = () => {
    // 清除定时器和请求
    if (copilotTimerRef.current) {
      clearTimeout(copilotTimerRef.current);
    }
    if (abortControllerRef.current && !abortControllerRef.current.signal.aborted) {
      abortControllerRef.current.abort();
    }

    try {
      const defaultCursor = document.querySelector('.cursors-layer .cursor') as HTMLDivElement;
      if (defaultCursor) {
        defaultCursor.style.display = 'block';
      }

      setCursorLoading({
        left: 0,
        top: 0,
        visible: 'hidden'
      });
    } catch (error) {
      console.warn('切换到默认光标失败:', error);
    }

    // 降级到原有方案
    if (editorRef.current) {
      editorRef.current.updateOptions({ readOnly: false });
      document.body.style.cursor = 'default';
    }
  };

  // 判断是否应该触发AI补全
  const shouldTriggerCompletion = (prefixContent: string, suffixContent: string, context: any): boolean => {
    // 如果前缀内容太短，不触发补全
    if (prefixContent.length < 1) {
      return false;
    }

    // 对于手动触发，总是允许
    if (context.triggerKind === 0) { // Manual trigger
      return true;
    }

    // 对于自动触发，更宽松的条件
    if (context.triggerKind === 1) { // Automatic trigger
      // 简化触发条件，只要有内容就可以触发
      return prefixContent.trim().length > 0;
    }

    return true;
  };



  // 编辑器选项配置
  const editorOptions: any = {
    selectOnLineNumbers: true,
    roundedSelection: false,
    readOnly: false,
    cursorStyle: 'line',
    automaticLayout: true,
    minimap: { enabled: settings.enableMinimap },
    fontSize: settings.fontSize,
    lineNumbers: settings.showLineNumbers ? 'on' : 'off',
    scrollBeyondLastLine: false,
    wordWrap: settings.wordWrap ? 'on' : 'off',
    tabSize: 4,
    insertSpaces: true,
    // 内置代码提示设置（独立于AI补全）
    suggestOnTriggerCharacters: settings.enableCodeSuggestions,
    quickSuggestions: settings.enableCodeSuggestions ? {
      other: true,
      comments: true,
      strings: true
    } : false,
    parameterHints: { enabled: settings.enableCodeSuggestions },
    formatOnPaste: settings.formatOnPaste,
    formatOnType: true,
    autoIndent: settings.autoIndent ? 'full' : 'none',
    dragAndDrop: true,
    links: true,
    mouseWheelZoom: settings.mouseWheelZoom,
    multiCursorModifier: 'alt',
    renderLineHighlight: 'all',
    acceptSuggestionOnCommitCharacter: settings.enableCodeSuggestions,
    acceptSuggestionOnEnter: settings.enableCodeSuggestions ? 'on' : 'off',
    // 启用内联补全功能（AI代码补全，显示为灰色字体）
    inlineSuggest: {
      enabled: settings.enableAICompletion,
      mode: 'prefix',
      suppressSuggestions: false
    },
    // 普通代码提示配置（不显示灰色预览）
    suggest: {
      preview: false, // 禁用普通提示的预览，避免灰色字体
      showInlineDetails: true,
      insertMode: 'insert',
      filterGraceful: true,
      snippetsPreventQuickSuggestions: false // 确保代码片段不会阻止快速建议
    }
  };

  // 编辑器加载完成回调
  const handleEditorDidMount = (editor: any, monacoInstance: typeof monaco) => {
    editorRef.current = editor;
    monacoRef.current = monacoInstance;
    setEditorLoading(false);
    setEditorMounted(true);

    // 初始化 TypeScript 配置
    initializeTypeScriptDefaults();

    // 注册AI代码补全提供器
    keyDownDisposableRef.current = editor.onKeyDown(switchToDefaultCursor);
    mouseDownDisposableRef.current = editor.onMouseDown(switchToDefaultCursor);

    // 为所有支持的语言注册内联补全提供器
    const supportedLanguages = ['cpp', 'python', 'java', 'javascript', 'typescript'];

    inlineCompletionDisposeRef.current = monacoInstance.languages.registerInlineCompletionsProvider(supportedLanguages, {
      provideInlineCompletions: (model, position, context, token) => {
        return new Promise((resolve) => {
          // 清除之前的定时器
          if (copilotTimerRef.current) {
            clearTimeout(copilotTimerRef.current);
          }

          // 取消之前的请求
          if (abortControllerRef.current && !abortControllerRef.current.signal.aborted) {
            abortControllerRef.current.abort();
          }

          // 使用设置中的延迟时间
          copilotTimerRef.current = window.setTimeout(async () => {
            try {
              // 获取光标前的代码（前缀）
              const prefixContent = model.getValueInRange({
                startLineNumber: 1,
                startColumn: 1,
                endLineNumber: position.lineNumber,
                endColumn: position.column,
              });

              // 获取光标后的代码（后缀）
              const suffixContent = model.getValueInRange({
                startLineNumber: position.lineNumber,
                startColumn: position.column,
                endLineNumber: model.getLineCount(),
                endColumn: model.getLineMaxColumn(model.getLineCount()),
              });

              // 检查是否需要触发补全（考虑设置）
              if (!shouldTriggerCompletionWithSettings(prefixContent, suffixContent, context)) {
                console.log('不满足补全触发条件，跳过补全', {
                  prefixLength: prefixContent.length,
                  triggerKind: context.triggerKind,
                  aiCompletionEnabled: settings.enableAICompletion
                });
                resolve({ items: [] });
                return;
              }

              // 获取当前实时的语言设置（从Monaco模型中获取）
              const currentLanguage = model.getLanguageId();

              console.log('触发AI补全', {
                prefixLength: prefixContent.length,
                suffixLength: suffixContent.length,
                triggerKind: context.triggerKind,
                prefix: prefixContent.slice(-20), // 显示最后20个字符
                currentLanguage: currentLanguage, // 使用实时语言信息
                stateLanguage: language // 对比状态中的语言
              });

              switchToLoadingCursor();
              abortControllerRef.current = new AbortController();

              // 调用AI补全服务
              console.log('准备调用AI补全API，语言参数:', currentLanguage);
              const response = await aiApi.chatOneAIGC({
                prefixContent,
                suffixContent,
                language: currentLanguage
              });

              if (response.code === 1 && response.data && response.data.length > 0) {
                const completions = response.data
                  .filter((content: string) => content !== null && content !== undefined)
                  .map((content: string, index: number) => {
                    // 完全保留AI返回的原始内容，包括空字符串、空格、换行符等
                    console.log('AI补全原始内容:', JSON.stringify(content));
                    return {
                      insertText: content,
                      range: {
                        startLineNumber: position.lineNumber,
                        startColumn: position.column,
                        endLineNumber: position.lineNumber,
                        endColumn: position.column,
                      },
                      // 添加必要的属性以确保补全显示
                      command: undefined,
                      additionalTextEdits: undefined
                    };
                  });

                console.log('AI补全结果数量:', completions.length);
                console.log('AI补全详细内容:', completions);

                // 确保返回正确的格式
                const result = { items: completions };
                console.log('返回给Monaco的补全结果:', result);
                resolve(result);
              } else {
                resolve({ items: [] });
              }
            } catch (error) {
              console.error('AI补全请求失败:', error);
              resolve({ items: [] });
            } finally {
              switchToDefaultCursor();
            }
          }, settings.completionDelay); // 使用设置中的延迟时间
        });
      },

      freeInlineCompletions(completions) {
        console.log('AI补全释放:', completions);
      },

      handleItemDidShow(completions) {
        console.log('AI补全显示:', completions);
      },
    } as monaco.languages.InlineCompletionsProvider);

    console.log('Monaco编辑器挂载完成');
  };

  // 暴露方法给父组件
  useImperativeHandle(ref, () => ({
    handleRunCode,
    handleSubmitCode
  }));

  return (
    <div className="code-editor" style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
      <div className="editor-toolbar" style={{ marginBottom: '16px', marginTop: '16px', marginLeft: '12px' }}>
        <Space>
          <Select
            value={language}
            style={{ width: 120 }}
            onChange={handleLanguageChange}
          >
            <Option value="cpp">C++</Option>
            <Option value="python">Python</Option>
            <Option value="java">Java</Option>
            <Option value="javascript">JavaScript</Option>
          </Select>
          <Select
            value={theme}
            style={{ width: 120 }}
            onChange={handleThemeChange}
          >
            <Option value="vs-dark">暗色主题</Option>
            <Option value="vs">浅色主题</Option>
          </Select>
          <Button
            icon={<CommentOutlined />}
            onClick={handleAIComment}
            loading={commentLoading}
            title="AI智能注释"
            type="default"
          >
            AI注释
          </Button>
          <Button
            icon={<SettingOutlined />}
            onClick={() => setSettingsVisible(true)}
            title="编辑器设置"
          >
            设置
          </Button>
        </Space>
      </div>
      <div style={{ flexGrow: 1, height: 'calc(100% - 66px)', position: 'relative' }}>
        {editorLoading && (
          <div style={{
            position: 'absolute',
            top: 0,
            left: 0,
            right: 0,
            bottom: 0,
            display: 'flex',
            justifyContent: 'center',
            alignItems: 'center',
            backgroundColor: 'rgba(255, 255, 255, 0.9)',
            zIndex: 10
          }}>
            <Spin tip="编辑器加载中..." size="large">
          <div style={{ minHeight: '400px' }} />
        </Spin>
          </div>
        )}
        {editorError && (
          <div style={{
            position: 'absolute',
            top: 0,
            left: 0,
            right: 0,
            bottom: 0,
            display: 'flex',
            justifyContent: 'center',
            alignItems: 'center',
            flexDirection: 'column',
            padding: '20px',
            backgroundColor: '#fff',
            zIndex: 10
          }}>
            <h3 style={{ color: 'red' }}>编辑器加载失败</h3>
            <p>{editorError}</p>
            <Button type="primary" onClick={() => window.location.reload()}>刷新页面</Button>
          </div>
        )}
        <MonacoEditor
          width="100%"
          height="100%"
          language={language}
          theme={theme}
          value={code}
          options={editorOptions}
          onChange={handleEditorChange}
          editorDidMount={handleEditorDidMount}
        />
        {/* 使用Portal渲染loading光标到Monaco Editor的光标层 */}
        {editorMounted && (() => {
          const cursorLayer = document.querySelector('.monaco-editor .cursors-layer');
          return cursorLayer ? ReactDOM.createPortal(
            <Spin
              className="cursorLoading"
              style={{
                position: 'absolute',
                top: cursorLoading.top,
                left: cursorLoading.left,
                visibility: cursorLoading.visible,
                zIndex: 999,
                pointerEvents: 'none'
              }}
              indicator={<LoadingOutlined spin />}
              size="small"
            />,
            cursorLayer
          ) : null;
        })()}
      </div>

      {/* 设置面板 */}
      <Drawer
        title="编辑器设置"
        placement="right"
        onClose={() => setSettingsVisible(false)}
        open={settingsVisible}
        width={350}
      >
        <Space direction="vertical" style={{ width: '100%' }} size="large">
          {/* AI功能设置 */}
          <div>
            <h4>AI功能</h4>
            <Space direction="vertical" style={{ width: '100%' }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <span>启用AI代码补全</span>
                <Switch
                  checked={settings.enableAICompletion}
                  onChange={(checked) => handleSettingChange('enableAICompletion', checked)}
                />
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <span>启用内置代码提示</span>
                <Switch
                  checked={settings.enableCodeSuggestions}
                  onChange={(checked) => handleSettingChange('enableCodeSuggestions', checked)}
                />
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <span>AI补全延迟时间 (毫秒)</span>
                <InputNumber
                  min={100}
                  max={5000}
                  step={100}
                  value={settings.completionDelay}
                  onChange={(value) => handleSettingChange('completionDelay', value || 1500)}
                  style={{ width: 100 }}
                  disabled={!settings.enableAICompletion}
                />
              </div>
              <div style={{
                padding: '8px 12px',
                backgroundColor: '#f5f5f5',
                borderRadius: '4px',
                fontSize: '12px',
                color: '#666'
              }}>
                💡 提示：AI注释功能会分析您的代码并自动在关键行末尾添加注释
              </div>
            </Space>
          </div>

          <Divider />

          {/* 编辑器外观设置 */}
          <div>
            <h4>编辑器外观</h4>
            <Space direction="vertical" style={{ width: '100%' }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <span>显示迷你地图</span>
                <Switch
                  checked={settings.enableMinimap}
                  onChange={(checked) => handleSettingChange('enableMinimap', checked)}
                />
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <span>显示行号</span>
                <Switch
                  checked={settings.showLineNumbers}
                  onChange={(checked) => handleSettingChange('showLineNumbers', checked)}
                />
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <span>字体大小</span>
                <InputNumber
                  min={10}
                  max={30}
                  value={settings.fontSize}
                  onChange={(value) => handleSettingChange('fontSize', value || 14)}
                  style={{ width: 80 }}
                />
              </div>
            </Space>
          </div>

          <Divider />

          {/* 编辑器行为设置 */}
          <div>
            <h4>编辑器行为</h4>
            <Space direction="vertical" style={{ width: '100%' }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <span>自动换行</span>
                <Switch
                  checked={settings.wordWrap}
                  onChange={(checked) => handleSettingChange('wordWrap', checked)}
                />
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <span>自动缩进</span>
                <Switch
                  checked={settings.autoIndent}
                  onChange={(checked) => handleSettingChange('autoIndent', checked)}
                />
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <span>粘贴时格式化</span>
                <Switch
                  checked={settings.formatOnPaste}
                  onChange={(checked) => handleSettingChange('formatOnPaste', checked)}
                />
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <span>鼠标滚轮缩放</span>
                <Switch
                  checked={settings.mouseWheelZoom}
                  onChange={(checked) => handleSettingChange('mouseWheelZoom', checked)}
                />
              </div>
            </Space>
          </div>

          <Divider />

          {/* 重置按钮 */}
          <Button
            type="dashed"
            block
            onClick={() => {
              setSettings({
                enableAICompletion: true,
                enableCodeSuggestions: true,
                completionDelay: 1500,
                enableMinimap: true,
                fontSize: 14,
                showLineNumbers: true,
                wordWrap: true,
                autoIndent: true,
                formatOnPaste: true,
                mouseWheelZoom: true
              });
              message.success('设置已重置为默认值');
            }}
          >
            重置为默认设置
          </Button>
        </Space>
      </Drawer>
    </div>
  );
});

export default CodeEditor;